<?php

class authentication extends controller {

    public function index() {
        
    }

    public function login() {
        $user = $this->getUser();
        $user->setEmail(trim($_POST['email']));
        $user->setPassword(trim($_POST['password']));
        $logged = $user->login();

        if ($logged)
            $this->redirect();
        else
            $this->redirect('/authentication/?error=true');
    }

    public function logout() {
        $this->getUser()->logout();
        $this->redirect();
    }
    
    public function cadastro() {
        #============Validação de campos =============#
        $valida = "/^[a-z0-9_\.\-]+@[a-z0-9_\.\-]*[a-z0-9_\-]+\.[a-z]{2,4}$/i";
        $register = array();

        if (isset($_POST['nome'])) {
            $register['firstname'] = trim($_POST['nome']);
        }

        if (isset($_POST['sobrenome'])) {
            $register['lastname'] = trim($_POST['sobrenome']);
        }

        if (isset($_POST['email'])) {
            $register['email'] = trim($_POST['email']);
        }

        if (isset($_POST['password'])) {
            $register['password'] = md5(trim($_POST['password']));
        }
        
        if (!preg_match ("/^[a-z0-9_\.\-]+@[a-z0-9_\.\-]*[a-z0-9_\-]+\.[a-z]{2,4}$/i", $register['email'])) {
            $this->redirect('/authentication/?msg=invalido');
        }
        
        $database = new database();

        $resultEmail = $database->select()
                ->from('user')
                ->where(email, $register['email'])
                ->execute();
        
        if(mysql_num_rows($resultEmail) == 1){
            $this->redirect('/authentication/?msg=emuso');
        }

        foreach ($register as $campo => $valor) {
            if (!$valor)
                $this->redirect('/authentication/?msg=' . $campo);
        }

        $db = new database();

        $db->insert('user', $register);
        
        $insere = $db->execute();
        
          if ($insere){
              $this->redirect('/authentication/?msg=sucesso');
          } else{
            $this->redirect('/authentication/?msg=erro');
          }

        #=============================================#
    }

}

?>
